package com.wen.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wen.mall.dao.ProductDao;
import com.wen.mall.enums.ProductEnum;
import com.wen.mall.enums.ResponseEnum;
import com.wen.mall.pojo.Product;
import com.wen.mall.service.CategoryService;
import com.wen.mall.service.ProductService;
import com.wen.mall.vo.ProductDetailVo;
import com.wen.mall.vo.ProductVo;
import com.wen.mall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductDao productDao;

    @Override
    public ResponseVo<PageInfo> list(Integer categoryId, Integer pageNum, Integer pageSize) {
        Set<Integer> categoryIdSet = new HashSet<>();
        if (categoryId != null) {
            categoryService.findSubcategoryId(categoryId, categoryIdSet);
            categoryIdSet.add(categoryId);
        }
        PageHelper.startPage(pageNum, pageSize);

        List<Product> productList = productDao.findBySubcategoryIdSet(categoryIdSet.size() == 0 ? null : categoryIdSet);
        List<ProductVo> productVoList = productList
                .stream().map(
                        e -> {
                            ProductVo productVo = new ProductVo();
                            BeanUtils.copyProperties(e, productVo);
                            return productVo;
                        }).collect(Collectors.toList());
        PageInfo pageInfo = new PageInfo<>(productList);
        pageInfo.setList(productVoList);
        return ResponseVo.success(pageInfo);
    }

    @Override
    public ResponseVo<ProductDetailVo> detail(Integer productId) {
        Product product = productDao.findById(productId);
        ProductDetailVo productDetailVo = new ProductDetailVo();
        BeanUtils.copyProperties(product, productDetailVo);
        log.info("productDetailVo.getStatus()=>" + productDetailVo.getStatus());
        if (productDetailVo.getStatus().equals(ProductEnum.OFF_SALE.getCode()) || productDetailVo.getStatus().equals(ProductEnum.DELETE.getCode())) {
            return ResponseVo.error(ResponseEnum.PRODUCT_OFF_SALE_DELETE);
        }
        productDetailVo.setStock(productDetailVo.getStock() > 100 ? 100 : productDetailVo.getStock()
        );
        return ResponseVo.success(productDetailVo);
    }
}
